package com.zhiqianbao.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiqianbao.R;
import com.zhiqianbao.entity.AppManage;
import com.zhiqianbao.entity.CustomerService;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.SystemUtils;
import com.zhiqianbao.utils.WorthPurseUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by Administrator on 2015/12/22.
 */
public class MineActivity extends BaseActivity {
    private static String TAG = MineActivity.class.getSimpleName();

    /**
     * 客服中心
     */
    RelativeLayout relativeLayoutMoreMessageKf;
    /**
     * 消息中心
     */
    RelativeLayout relativeLayoutMoreMessageCenter;
    /**
     * 借款须知
     */
    RelativeLayout relativeLayoutMoreBorrowingRequirements;
    /**
     * 还款须知
     */
    RelativeLayout relativeLayoutMoreReimbursementInstructions;
    /**
     * 关于
     */
    RelativeLayout relativeLayoutMoreP2p2loanAboutus;
    /**
     * 分享
     */
    RelativeLayout relativeLayoutMoreP2p2loanShare;

    /**
     * 推荐应用
     */
    RelativeLayout relativeLayoutRecommendedApp;

    /**
     * 检查更新
     */
    RelativeLayout relativeLayoutMoreP2p2loanVersion;

    private RelativeLayout rl_activity;
    private TextView noannouncement_counts_tv;

    /**
     * 显示版本号
     */
    TextView tvVersion;
    /**
     * 是否有新版本更新的显示
     */
    TextView tvNeedUpdate;

    /**
     * 客服未读条数
     */
    TextView viewMessagekf;
    /**
     * 消息未读数量
     */
    TextView viewMessagecenter;
    /**
     * 连续点击配置测试地址和正式地址切换
     */
    Button btWeburlConfig;

    EditText edittext_web;
    EditText edittext_api;

    int versionCode;
    int newVersionCode;
    ProgressDialog pd = null;
    String UPDATE_SERVERAPK = "mimidai.apk";
    //数组存储点击次数
    long[] mHits = null;
    private Dialog connectionAdressDialog;
    private SharedPreferanceUtils sharedPreferanceUtils;
    Handler messageStatehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
//                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<CustomerService> data = (Result<CustomerService>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            CustomerService customerService = data.getData();
                            if (null != customerService) {
                                int noRead = customerService.getUserNoRead();
                                if (noRead > 0) {
                                    viewMessagekf.setVisibility(View.VISIBLE);
                                    viewMessagekf.setText(noRead + "");
                                } else {
                                    viewMessagekf.setVisibility(View.GONE);
                                }
                            } else {
                                viewMessagekf.setVisibility(View.GONE);
                            }
                        }
                        else{
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };
    Handler sysMssageStatehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
//                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<Long> data = (Result<Long>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            Long sysMessageSize = data.getData();
                            if (null != sysMessageSize) {

                                if (sysMessageSize > 0) {
                                    viewMessagecenter.setVisibility(View.VISIBLE);
                                    viewMessagecenter.setText(sysMessageSize + "");
                                } else {
                                    viewMessagecenter.setVisibility(View.GONE);
                                }
                            } else {
                                viewMessagecenter.setVisibility(View.GONE);
                            }
                        }
                        else{
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };
    Handler isNeedUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
//                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<Integer> data = (Result<Integer>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            //系统版本
                            newVersionCode = data.getData();
                            //需要更新
                            if (newVersionCode > versionCode) {
                                tvNeedUpdate.setVisibility(View.VISIBLE);
                            } else {
                                tvNeedUpdate.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };

    Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
//                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<AppManage> data = (Result<AppManage>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            AppManage appManage = data.getData();
                            if (appManage != null) {
                                if (appManage.getVersionCode() > versionCode) {
                                    doNewVersionUpdate(appManage.getVersionName(), appManage.getAppUrl());
                                } else {
                                    notNewVersionUpdate();
                                }
                            } else {
                                notNewVersionUpdate();
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        init();
        initView();
    }


    private void initView() {
         relativeLayoutMoreMessageKf=(RelativeLayout)findViewById(R.id.relativeLayout_more_message_kf);
         relativeLayoutMoreMessageCenter=(RelativeLayout)findViewById(R.id.relativeLayout_more_message_center);
         relativeLayoutMoreBorrowingRequirements=(RelativeLayout)findViewById(R.id.relativeLayout_more_borrowing_requirements);
         relativeLayoutMoreReimbursementInstructions=(RelativeLayout)findViewById(R.id.relativeLayout_more_reimbursement_instructions);
         relativeLayoutMoreP2p2loanAboutus=(RelativeLayout)findViewById(R.id.relativeLayout_more_p2p2loan_aboutus);
         relativeLayoutMoreP2p2loanShare=(RelativeLayout)findViewById(R.id.relativeLayout_more_p2p2loan_share);
         relativeLayoutRecommendedApp=(RelativeLayout)findViewById(R.id.relativeLayout_recommended_app);
         relativeLayoutMoreP2p2loanVersion=(RelativeLayout)findViewById(R.id.relativeLayout_more_p2p2loan_version);
         tvVersion=(TextView)findViewById(R.id.tv_version);
         tvNeedUpdate=(TextView)findViewById(R.id.tv_need_update);
         viewMessagekf=(TextView)findViewById(R.id.view_messagekf);
         viewMessagecenter=(TextView)findViewById(R.id.view_messagecenter);
         btWeburlConfig=(Button)findViewById(R.id.bt_weburl_config);
        versionCode = SystemUtils.getVersionCode(MineActivity.this);
        tvVersion.setText(Constants.APP_VERSION);
        rl_activity = (RelativeLayout) findViewById(R.id.rl_activity);
        noannouncement_counts_tv = (TextView) findViewById(R.id.noannouncement_counts_tv);
        ButtonListener listener = new ButtonListener();
        relativeLayoutMoreBorrowingRequirements.setOnClickListener(listener);
        relativeLayoutMoreReimbursementInstructions.setOnClickListener(listener);
        relativeLayoutMoreP2p2loanShare.setOnClickListener(listener);
        relativeLayoutMoreMessageCenter.setOnClickListener(listener);
        relativeLayoutMoreMessageKf.setOnClickListener(listener);
        relativeLayoutRecommendedApp.setOnClickListener(listener);
        relativeLayoutMoreP2p2loanVersion.setOnClickListener(listener);
        relativeLayoutMoreP2p2loanAboutus.setOnClickListener(listener);
        btWeburlConfig.setOnClickListener(listener);
        rl_activity.setOnClickListener(listener);
    }

    // 首先在您的Activity中添加如下成员变量
    // final UMSocialService  mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(R.id.rl_activity==v.getId()) {
                    startActivity(new Intent(MineActivity.this, LatestAnmentActivity.class));

            }
            else if(R.id.relativeLayout_more_borrowing_requirements==v.getId()) {
                Intent borrowIntent = new Intent(MineActivity.this, DialogContractActivity.class);
                borrowIntent.putExtra("url", "/webview/applyNotice");
                borrowIntent.putExtra("title", "借款须知");
                startActivity(borrowIntent);
            }
            else if(R.id.relativeLayout_more_reimbursement_instructions==v.getId()) {
                    Intent reimbursementIntent = new Intent(MineActivity.this, DialogContractActivity.class);
                    reimbursementIntent.putExtra("url", "/webview/repaymentNotice");
                    reimbursementIntent.putExtra("title", "还款须知");
                    startActivity(reimbursementIntent);
            }
            else if(R.id.relativeLayout_more_p2p2loan_aboutus==v.getId()) {
                    Intent aboutIntent = new Intent(MineActivity.this, DialogContractActivity.class);
                    aboutIntent.putExtra("url", "/webview/about");
                    aboutIntent.putExtra("title", "关于米米贷");
                    startActivity(aboutIntent);
            }
            else if(R.id.relativeLayout_more_p2p2loan_share==v.getId()) {

            }
            else if(R.id.relativeLayout_more_message_center==v.getId()) {
                //消息中心
                    if (Constants.LOGIN_USER != null) {
                        startActivity(new Intent(MineActivity.this, SysMessageMainActivity.class));
                    } else {
                        Intent mine1 = new Intent(MineActivity.this,
                                WorthPurseUtil.getZhiddActivity().getClass());
                        startActivity(mine1);
                        finish();
                    }
//                    CheckUtils.checkUserState(MineActivity.this, SysMessageMainActivity.class);
            }
            else if(R.id.relativeLayout_more_message_kf==v.getId()) {
//                    CheckUtils.checkUserState(MineActivity.this, MessageMainActivity.class);
                    if (Constants.LOGIN_USER != null) {
                        startActivity(new Intent(MineActivity.this, MessageMainActivity.class));
                    } else {
                        Intent mine1 = new Intent(MineActivity.this,
                               WorthPurseUtil.getZhiddActivity().getClass());
                        startActivity(mine1);
                        finish();
                    }
            }
            else if(R.id.relativeLayout_more_p2p2loan_version==v.getId()) {
                  /*  int versionCode = SystemUtils.getVersionCode(MineActivity.this);
                    Log.i(TAG, "versionCode :" + versionCode);
                    //调用下载检查接口
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String channelCode = Constants.CHANNEL_CODE;
                            Map<String, String> params = new HashMap<>();
                            params.put("channelCode", channelCode);
                            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/updateApp", params, MineActivity.this);
                            Message message = new Message();
                            if (StringUtils.isBlank(result)) {
                                message.what = RESULT_CANCELED;
                            } else {
                                message.what = RESULT_OK;
                                Result<AppManage> data = Result.fromJson(result, AppManage.class);
                                message.obj = data;
                            }
                            updateHandler.sendMessage(message);
                        }
                    }).start();*/
//                    UmengUpdateAgent.forceUpdate(MineActivity.this);
            }
            else if(R.id.relativeLayout_recommended_app==v.getId()) {
                    Intent recommendAppIntent = new Intent(MineActivity.this, RecommendAppActivity.class);
                    recommendAppIntent.putExtra("url", "/webview/recommended");
                    recommendAppIntent.putExtra("title", "推荐应用");
                    startActivity(recommendAppIntent);
            }
            else if(R.id.bt_weburl_config==v.getId()){
                    //onDisplaySettingButton();
            }
        }
    }

    /**
     * 连续点击7次出现弹出框
     */
    public void onDisplaySettingButton() {
        if (mHits == null) {
            mHits = new long[8];
        }
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);//把从第二位至最后一位之间的数字复制到第一位至倒数第一位
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//记录一个时间
        if (SystemClock.uptimeMillis() - mHits[0] <= 1600) {//一秒内连续点击。
            mHits = null;    //这里说明一下，我们在进来以后需要还原状态，否则如果点击过快，第六次，第七次 都会不断进来触发该效果。重新开始计数即可
            showDialog();
        }
    }
    /**
     * 显示分享弹出框
     */
    private void showDialog() {
        if (connectionAdressDialog == null) {
            switchConnectionAdress();
        }
        connectionAdressDialog.show();
    }
    /**
     * 切换网络地址弹出框
     */
    public void switchConnectionAdress() {
        connectionAdressDialog = new Dialog(this, R.style.dialog_bottom_full);
        connectionAdressDialog.setCanceledOnTouchOutside(true);
        connectionAdressDialog.setCancelable(true);
        Window window = connectionAdressDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(this, R.layout.dialog_connection_adress_layout, null);
        TextView adress_one = (TextView) view.findViewById(R.id.adress_one);
        TextView adress_two = (TextView) view.findViewById(R.id.adress_two);
        TextView adress_three = (TextView) view.findViewById(R.id.adress_three);
        TextView adress_four = (TextView) view.findViewById(R.id.adress_four);
        edittext_web = (EditText) view.findViewById(R.id.edittext_web);
        edittext_api = (EditText) view.findViewById(R.id.edittext_api);
        TextView edit_sure = (TextView) view.findViewById(R.id.edit_sure);
        TextView connection_cancel = (TextView) view.findViewById(R.id.connection_cancel);
        defaultNowConnectionAdress(adress_one,adress_two,adress_three,adress_four);
        adress_one.setOnClickListener(connectionClick);
        adress_two.setOnClickListener(connectionClick);
        adress_three.setOnClickListener(connectionClick);
        adress_four.setOnClickListener(connectionClick);
        edit_sure.setOnClickListener(connectionClick);
        connection_cancel.setOnClickListener(connectionClick);
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }

    View.OnClickListener connectionClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(R.id.adress_one==v.getId()) {
                    SharedPreferanceUtils.setClear();
                    sharedPreferanceUtils.setWebAdress("http://192.168.1.63:81/mimidai-web");
                    sharedPreferanceUtils.setApiAdress("http://192.168.1.63:81/mimidai-api");
                    Constants.WEB_ROOT = "http://192.168.1.63:81/mimidai-web";
                    Constants.API_ROOT = "http://192.168.1.63:81/mimidai-api";
                    startApp();
            }
            else if(R.id.adress_two==v.getId()) {
                    SharedPreferanceUtils.setClear();
                    sharedPreferanceUtils.setWebAdress("http://192.168.1.60:81/mimidai-web");
                    sharedPreferanceUtils.setApiAdress("http://192.168.1.60:81/mimidai-api");
                    Constants.WEB_ROOT = "http://192.168.1.60:81/mimidai-web";
                    Constants.API_ROOT = "http://192.168.1.60:81/mimidai-api";
                    startApp();
            }
            else if(R.id.adress_three==v.getId()) {
                    SharedPreferanceUtils.setClear();
                    sharedPreferanceUtils.setWebAdress("https://line.mimidai.com/mimidai-web");
                    sharedPreferanceUtils.setApiAdress("https://line.mimidai.com/mimidai-api");
                    Constants.WEB_ROOT = "https://line.mimidai.com/mimidai-web";
                    Constants.API_ROOT = "https://line.mimidai.com/mimidai-api";
                    startApp();
            }
            else if(R.id.adress_four==v.getId()) {
                    SharedPreferanceUtils.setClear();
                    sharedPreferanceUtils.setWebAdress("https://www.mimidai.com");
                    sharedPreferanceUtils.setApiAdress("https://api.mimidai.com");
                    Constants.WEB_ROOT = "https://www.mimidai.com";
                    Constants.API_ROOT = "https://api.mimidai.com";
                    startApp();
            }
            else if(R.id.edit_sure==v.getId()) {
                    SharedPreferanceUtils.setClear();
                    sharedPreferanceUtils.setWebAdress(edittext_web.getText().toString());
                    sharedPreferanceUtils.setApiAdress(edittext_api.getText().toString());
                    startApp();
            }
            else if(R.id.connection_cancel==v.getId()){

            }
            if (connectionAdressDialog != null && connectionAdressDialog.isShowing()) {
                connectionAdressDialog.dismiss();
            }
        }
    };

    /**
     * 重新启动app
     */
    public void startApp(){
        //清除登录用户缓存
        Constants.LOGIN_USER = null;
        //清除自动登录缓冲内容
        FileUtils.deleteCache("apply.txt");
        FileUtils.deleteCache("user.txt");
        sharedPreferanceUtils.setAuto(false);
        Intent i = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage( getBaseContext().getPackageName() );
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);

    }

    /**
     * 默认当前链接服务器地址
     */
    public void defaultNowConnectionAdress(TextView tv1,
             TextView tv2,TextView tv3,TextView tv4){
        String api_url=sharedPreferanceUtils.getApiAdress();
        if(api_url.equals("http://192.168.1.63:81/mimidai-api")){
            tv1.setBackgroundColor(Color.parseColor("#DB3C22"));
            tv1.setTextColor(Color.parseColor("#ffffff"));
        }
        else if(api_url.equals("http://192.168.1.60:81/mimidai-api")){
            tv2.setBackgroundColor(Color.parseColor("#DB3C22"));
            tv2.setTextColor(Color.parseColor("#ffffff"));
        }
        else if(api_url.equals("https://line.mimidai.com/mimidai-api")){
            tv3.setBackgroundColor(Color.parseColor("#DB3C22"));
            tv3.setTextColor(Color.parseColor("#ffffff"));
        }
        else if(api_url.equals("https://api.mimidai.com")){
            tv4.setBackgroundColor(Color.parseColor("#DB3C22"));
            tv4.setTextColor(Color.parseColor("#ffffff"));
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferanceUtils sharedPreferanceUtils =
                new SharedPreferanceUtils(MineActivity.this);
        int noReadCounts = sharedPreferanceUtils.getNoAnnouncementCounts();
        if (noReadCounts != 0) {
            noannouncement_counts_tv.setVisibility(View.VISIBLE);
            noannouncement_counts_tv.setText(noReadCounts + "");
        } else {
            noannouncement_counts_tv.setVisibility(View.GONE);
        }
        //处于登录状态
        if (Constants.LOGIN_USER != null) {
            //调用查询客服状态的接口
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/getMessageState", params, MineActivity.this);
                    Message message = new Message();
                    if (StringUtils.isBlank(result)) {
                        message.what = RESULT_CANCELED;
                    } else {
                        message.what = RESULT_OK;
                        Result<CustomerService> data = Result.fromJson(result, CustomerService.class);
                        message.obj = data;
                    }
                    messageStatehandler.sendMessage(message);
                }
            }).start();
            //调用查询系统消息未读数量的接口
            //调用查询客服状态的接口
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Map<String, String> params = new HashMap<>();
                    params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/message/noReadSysMsgSize", params, MineActivity.this);
                    Message message = new Message();
                    if (StringUtils.isBlank(result)) {
                        message.what = RESULT_CANCELED;
                    } else {
                        message.what = RESULT_OK;
                        Result<Long> data = Result.fromJson(result, Long.class);
                        message.obj = data;
                    }
                    sysMssageStatehandler.sendMessage(message);
                }
            }).start();
        }

        //每次到这个页面，检查一下是否存在新版本
      /*  new Thread(new Runnable() {
            @Override
            public void run() {

                String channelCode = Constants.CHANNEL_CODE;
                Map<String, String> params = new HashMap<>();
                params.put("channelCode", channelCode);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/checkNeedUpdate", params, MineActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<Integer> data = Result.fromJson(result, Integer.class);
                    message.obj = data;
                }
                isNeedUpdateHandler.sendMessage(message);
            }
        }).start();*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
//        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;
//        if(ssoHandler != null){
//            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//        }
    }

    long mExitTime;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
                mHomeIntent.addCategory(Intent.CATEGORY_HOME);
                mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivity(mHomeIntent);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 不更新版本
     */
    public void notNewVersionUpdate() {

        String verName = Constants.APP_VERSION;
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本：");
        sb.append(verName);
        sb.append("\n已是最新版本，无需更新");
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(sb.toString())
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create();
        dialog.show();
    }

    /**
     * 更新版本
     */
    public void doNewVersionUpdate(String newVerName, final String appUrl) {
        String verName = Constants.APP_VERSION;
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本：");
        sb.append(verName);
        sb.append(",发现版本：");
        sb.append(newVerName);
        sb.append(",是否更新");
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(sb.toString())
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        pd = new ProgressDialog(MineActivity.this);
                        pd.setTitle("正在下载");
                        pd.setMessage("请稍后...");
                        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        pd.setIndeterminate(false);
                        pd.setCanceledOnTouchOutside(false);
                        downFile(appUrl);
                    }
                })
                .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create();
        //显示更新框
        dialog.show();
    }

    /**
     * 下载apk
     */
    public void downFile(final String urlStr) {
        pd.show();
        new Thread() {
            public void run() {

                try {
                    URL url = new URL(urlStr);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //取得inputStream，并进行读取
                    InputStream is = conn.getInputStream();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        int charb = -1;
                        int count = 0;
                        while ((charb = is.read(b)) != -1) {
                            fileOutputStream.write(b, 0, charb);
                            count += charb;
                        }
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    down();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            pd.cancel();
            update();
        }
    };

    /**
     * 下载完成，通过handler将下载对话框取消
     */
    public void down() {
        new Thread() {
            public void run() {
                Message message = handler.obtainMessage();
                handler.sendMessage(message);
            }
        }.start();
    }

    /**
     * 安装应用
     */
    public void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK))
                , "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
